/**
 * @fileOverview
 * 名称搜索
 * @author iNahoo
 * @since 2022/3/6.
 */

import React, { useCallback, useMemo, useRef, useState } from 'react';
import { AutoComplete } from 'antd';


const NameFinder = props => {
  const {
    dataList,
    onChange
  } = props;

  const valStash = useRef('');
  const [options, setOptions] = useState([]);


  const wholeOptions = useMemo(() => {
    return [...new Set(dataList.map(r => r['素材']))].map(str => ({
      value: str
    }))
  }, [dataList]);

  const changeHandler = useCallback((val) => {
    console.log(val);
    valStash.current = val;

    if (!val) {
      setOptions([]);
    } else {
      const optList = wholeOptions.filter(i => i.value.match(val)).slice(0, 10);
      setOptions(optList);
    }

    onChange && onChange(val);
  }, [wholeOptions, onChange]);

  return (
    <>
      <AutoComplete
        onChange={changeHandler}
        options={options}
        defaultValue={valStash}
        clearIcon={true}
        placeholder={'输入素材名'}
      />
    </>
  );
};

export default NameFinder;
